package com.joey.user.controller;

import com.cloud.api.client.ItemOrder;
import com.cloud.api.dto.GoodsCategoryDto;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author: Joey
 * @Description:
 * @date:2024/6/25 18:41
 */
@RestController
@RequestMapping("/test")
@Slf4j
@Api(tags = "测试")
@RequiredArgsConstructor
public class TestController {

    private final ItemOrder itemOrder;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/c1")
    public String test1(){
        String msg = "测试mq消息1";
        rabbitTemplate.convertAndSend("cart.topic", "cart.success", msg);
        return "测试1";
    }

    @GetMapping("/mq1")
    public String test3(){
        // 1.创建CorrelationData 异步回调的返回回执
        CorrelationData cd = new CorrelationData();
        cd.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {
            @Override
            public void onFailure(Throwable ex) {
                // 2.1.Future发生异常时的处理逻辑，基本不会触发
                log.error("send message fail", ex);
            }
            @Override
            public void onSuccess(CorrelationData.Confirm result) {
                // 2.2.Future接收到回执的处理逻辑，参数中的result就是回执内容
                if(result.isAck()){ // result.isAck()，boolean类型，true代表ack回执，false 代表 nack回执
                    log.debug("发送消息成功，收到 ack!");
                }else{ // result.getReason()，String类型，返回nack时的异常描述
                    log.error("发送消息失败，收到 nack, reason : {}", result.getReason());
                }
            }
        });

        String msg = "测试mq发送消息的回执";//异步回调的返回回执
        rabbitTemplate.convertAndSend("cart.topic", "cart.success", msg, cd);
        return "mq-return-test";
    }

    @GetMapping("/c2")
    public List<GoodsCategoryDto> test2(){
        List<GoodsCategoryDto> goodsCategoryDtos = itemOrder.queryOrder3();
        System.out.println(goodsCategoryDtos);
        return goodsCategoryDtos;
    }

}
